<?php
namespace Home\Controller;
use Think\Controller;
class OrderController extends AuthController{
	/**
	 * 订单列表
	 */
	public function index(){
		$order = D("Order");
		$pageSize = 10;
		$store = session('store');
		$where['uid'] = $store['id'];
		$payment = I('payment');
		if($payment){
			$where['payment'] = $payment;
		}
		$status = I('status');
		if($status){
			$where['status'] = $status;
		}
		$sdate = I('sdate');
		if(!$sdate){
			$sdate = date("Y-m")."-01";	
		}
		$edate = I('edate');
		if(!$edate){
			$edate = date("Y-m-d");
		}
		$where['cdate'] = array("BETWEEN",array($sdate,$edate));
		$list 		= $order->relation(true)->where($where)->page($_GET['p'],$pageSize)->order('cdate desc,ctime desc')->select();
		$count      = $order->where($where)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,$pageSize);// 实例化分页类 传入总记录数和每页显示的记录数
		$Page->setConfig("next","下一页");
		$Page->setConfig("prev","上一页");
		$show       = $Page->show();// 分页显示输出
		$this->assign('page',$show);// 赋值分页输出
		$this->assign('totalPages',$Page->totalPages);// 总页数
		$this->assign('list',$list);
		
		
		/*
		 * 计算总价
		 */
		$result = M("Order")->where($where)->field("SUM(food_price) as total_price")->select();
		$total_price = $result[0]["total_price"];
		$this->assign('total_price',$total_price);
		
		/*
		 * 保存筛选条件
		 */
		$this->assign('sdate',$sdate);
		$this->assign('edate',$edate);
		$this->assign('payment',$payment);
		$this->assign('status',$status);
		$this->display();
	}
	public function again(){
		$where['oid'] = I('oid');
		$list = M("OrderDetail")->where($where)->select();
		$store = session('store');
		$uid = $store['id'];
		foreach ($list as $item){
			$result = M("FoodCategory")->where(array('id'=>$item['cid']))->find();
			if($result){
				$this->addCart($uid, $item['cid'], $item['num']);
			}else{
				$this->error("部分菜品已下架更新，请您重新订购！");
			}
		}
		$this->redirect("/Home/Cart/index");
	}
	public function addCart($uid,$cid,$num){
		$store = session('store');
		
		$data['uid'] = $uid;
		$data['cid'] = $cid;
		$data['cdate'] = date("Y-m-d");
		$where = $data;
		$cart = D('Cart');
		$item = $cart->where($where)->find();
		if($item){
			$data['num'] = $item['num']+$num;
			$result = $cart->where($where)->save($data);
			if($result){
				$json['result'] = 1;
				$json['msg'] = "添加到购物车成功";
			}else{
				$json['result'] = -1;
				$json['msg'] = "添加到购物车失败";
			}
		}else{
			$data['num'] = $num;
			$data = $cart->create($data);
			$result = $cart->add($data);
			if($result){
				$json['result'] = 1;
				$cartnum = $store['cartnum'] + 1;
				$json['cartnum'] = $cartnum;
				$store['cartnum'] = $cartnum;
				session('store',$store);
				$json['msg'] = "添加到购物车成功";
			}else{
				$json['result'] = -2;
				$json['msg'] = "添加到购物车失败";
			}
		}
	}
}